<?php
include_once 'config.db.php';
include_once 'Modelo/ErrorBD.php';

/*
 * Instrucciones de Uso: http://www.ricocheting.com/code/php/mysql-database-class-wrapper-v3
 */
class BD_MySQL{	
	private static $instance; // Store the single instance of Database
	
	private $server;
	private $user;
	private $pass;
	private $database;
	
	private	$link_id = 0;
	private	$query_id = 0;

	private	$error = null;
	
#-#############################################
# desc: constructor
private function __construct($server, $user, $pass, $database){
	$this->server=$server;
	$this->user=$user;
	$this->pass=$pass;
	$this->database=$database;
	$this->error = new ErrorBD_MySQL(TipoErrorBD::SIN_ERRORES);
}#-#constructor()

#-#############################################
# desc: singleton declaration
public static function getInstance(){
	if (!self::$instance){ 
		self::$instance = new BD_MySQL(BD::server, BD::user, BD::pass, BD::database); 
	} 
	return self::$instance; 
}

#-#############################################
# desc: connect and select database using vars above
# Param: $new_link can force connect() to open a new link, even if mysql_connect() was called before with the same parameters
public function connect($new_link=false){	
	$this->link_id=@mysql_connect($this->server,$this->user,$this->pass,$new_link);

	if (!$this->link_id){//open failed
		$this->error = new ErrorBD_MySQL(TipoErrorBD::SERVER_CONNECTION,$this->server);		
	}

	if(!@mysql_select_db($this->database, $this->link_id)){//no database
		$this->error = new ErrorBD_MySQL(TipoErrorBD::OPEN_DATABASE,$this->database);
	}
	
	// unset the data so it can't be dumped
	$this->server='';
	$this->user='';
	$this->pass='';
	$this->database='';
}#-#connect()

#-#############################################
# desc: close the connection
public function close(){
	if(!@mysql_close($this->link_id)){
		$this->error = new ErrorBD_MySQL(TipoErrorBD::CLOSE_DATABASE,$this->database);
	}
}#-#close()


#-#############################################
# Desc: escapes characters to be mysql ready
# Param: string
# returns: string
public function escape($string){
	if(get_magic_quotes_runtime()) $string = stripslashes($string);
	return mysql_real_escape_string($string,$this->link_id);
}#-#escape()


#-#############################################
# Desc: executes SQL query to an open connection
# Param: (MySQL query) to execute
# returns: (query_id) for fetching results etc
private function query($sql){
	// do query
	$this->query_id = @mysql_query($sql, $this->link_id);

	if (!$this->query_id){
		$this->error = new ErrorBD_MySQL(TipoErrorBD::QUERY_FAIL,$this->link_id,$sql);
		return 0;
	}
		
	return $this->query_id;
}#-#query()

public function truncateTable($tableName){
	$this->query("truncate $tableName");
}

public function getAffectedRowsBySelect(){
	return  mysql_num_rows($this->query_id);
}

public function getAffectedRowsByDML(){
	return mysql_affected_rows($this->link_id);
}

#-#############################################
# desc: does a query, fetches the first row only, frees resultset
# param: (MySQL query) the query to run on server
# returns: array of fetched results
public function getOneRowByQueryString($query_string){
	$query_id = $this->query($query_string);
	$out = false;
	if(!$this->hayError()){
		$out = $this->getOneRowByQueryID($query_id);
		//$this->free_result($query_id);	
	}
	return $out;
}#-#query_first()


#-#############################################
# desc: fetches and returns results one line at a time
# param: query_id for mysql run. if none specified, last used
# return: (array) fetched record(s)
public function getOneRowByQueryID($query_id=-1){
	// retrieve row
	if ($query_id!=-1){
		$this->query_id=$query_id;
	}

	if (isset($this->query_id)){
		$record = @mysql_fetch_assoc($this->query_id);
	}else{
		$this->error = new ErrorBD_MySQL(TipoErrorBD::FETCH_ERROR,$this->query_id);
		return false;
	}

	return $record;
}#-#getOneRow()


#-#############################################
# desc: returns all the results (not one row)
# param: (MySQL query) the query to run on server
# returns: assoc array of ALL fetched results
public function getAllRowsByQueryString($sql){
	$query_id = $this->query($sql);
	$out = array();

	while ($row = $this->getOneRowByQueryID($query_id)){
		$out[] = $row;
	}

	$this->free_result($query_id);
	return $out;
}#-#getAllRows()


#-#############################################
# desc: does an update query with an array
# param: table, assoc array with data (not escaped), where condition (optional. if none given, all records updated)
# returns: (query_id) for fetching results etc
public function update($table, $data, $where='1'){
	$q="UPDATE `$table` SET ";

	foreach($data as $key=>$val){
		if(strtolower($val)=='null') $q.= "`$key` = NULL, ";
		elseif(strtolower($val)=='now()') $q.= "`$key` = NOW(), ";
        elseif(preg_match("/^increment\((\-?\d+)\)$/i",$val,$m)) $q.= "`$key` = `$key` + $m[1], "; 
		else $q.= "`$key`='".$this->escape($val)."', ";
	}

	$q = rtrim($q, ', ') . ' WHERE '.$where.';';

	return $this->query($q);
}#-#update()


#-#############################################
# desc: does an insert query with an array
# param: table, assoc array with data (not escaped)
# returns: id of inserted record, false if error
public function insert($table, $data){
	$q="INSERT INTO `$table` ";
	$v=''; $n='';

	foreach($data as $key=>$val){
		$n.="`$key`, ";
		if(strtolower($val)=='null') $v.="NULL, ";
		elseif(strtolower($val)=='now()') $v.="NOW(), ";
		else $v.= "'".$this->escape($val)."', ";
	}

	$q .= "(". rtrim($n, ', ') .") VALUES (". rtrim($v, ', ') .");";

	if($this->query($q)){
		return mysql_insert_id($this->link_id);
	}
	else return false;

}#-#insert()


#-#############################################
# desc: frees the resultset
# param: query_id for mysql run. if none specified, last used
private function free_result($query_id=-1){
	if ($query_id!=-1){
		$this->query_id=$query_id;
	}
	if($this->query_id!=0 && !@mysql_free_result($this->query_id)){
		$this->error = new ErrorBD_MySQL(TipoErrorBD::FREE_RESULT,$this->query_id);
	}
}#-#free_result()

public function hayError(){
	$this->error->hayError();
}
public function getError(){
	return $this->error;
}

/* El formato debe ser YYYY-MM-DD
 * */

public function formatDate($fecha,$formatoIngresado) {
	switch ($formatoIngresado) {		
		case 'DD/MM/YYYY':
			return implode('-',array_reverse(explode('/',$fecha)));
		break;
		default:
			return $fecha;
		break;
	}
}

}//CLASS Database
###################################################################################################